<template>
  <!-- @touchstart="handleTouchStart"
    @touchmove="handleTouchMove" -->
  <!-- <div
    class="shadow-box"
    :class="{ 'shadow-box-move': store.previewModeShow }"
    :style="{ 'background-image': `url(${getFreeBackground})` }"
  ></div> -->
  <div
    class="home-box jy-style-height"
    :class="{
      'home-box-loop': route.meta.loopType ? true : false,
      'home-box-Android': store.isMobileType && isAndroidType,
      'home-box-Ios': store.isMobileType && !isAndroidType,
    }"
    id="edit-scroll-box"
    @scroll="scrollDom"
    ref="scrollRef"
    @mousewheel="pageWheel"
    @wheel="pageWheel"
    @contextmenu.stop="onContextMenuStop"
  >
    <div class="scroll-box jy-style-height" :id="'edit-box' + commonStore.templateId">
      <div
        v-if="store.resizeShow && store.previewMode === 1"
        ref="listContainer"
        class="scroll-box-item-parent scroll-box-item-parent-2"
        :style="{ 'background-image': `url(${getFreeBackground})` }"
      >
        <moveComponents v-if="commonStore.templateId == 651173498134597" />
        <posterComponent />
        <div
          id="free-outline-byid"
          class="scroll-box-item"
          ref="itemContainer"
          v-for="(item, index) in store.templateMOdeList"
          :key="item.id"
        >
          <Level1outline
            :scrollDom="scrollRef"
            :info="item"
            :indexs="index"
            :level1Id="Number(item.id)"
            :isShow="true"
          />
        </div>
        <Footer />
      </div>
      <div
        v-else-if="store.resizeShow && store.previewMode === 2"
        ref="listContainer"
        class="scroll-box-item-parent scroll-box-item-parent-mode"
        :style="{ 'background-image': `url(${getFreeBackground})` }"
      >
        <moveComponents v-if="commonStore.templateId == 651173498134597" />
        <posterComponent />

        <div
          class="free-item-style"
          @click="expandItem(item.id, index)"
          :class="{
            'free-item-move': index !== store.previewModuleIndex,
            'free-item-move-pw': index === store.previewModuleIndex,
          }"
          v-for="(item, index) in store.templateMOdeList"
          :key="item.id"
        >
          <div class="left-title-box" v-if="index !== store.previewModuleIndex">
            {{ item.text }}
          </div>
          <div id="free-outline-byid" class="scroll-box-item" ref="itemContainer">
            <!-- v-if="index === store.previewModuleIndex" -->

            <Level1outline
              v-if="index === store.previewModuleIndex"
              :scrollDom="scrollRef"
              :info="item"
              :indexs="index"
              :level1Id="Number(item.id)"
              :isShow="true"
            />
          </div>
        </div>
        <Footer />
        <!-- <nextModuleCom /> -->
        <!-- <Footer v-if="store.previewModuleIndex === store.templateMOdeList.length - 1" /> -->
      </div>
    </div>

    <progressCom
      v-if="!store.previewModeShow && store.previewMode !== 2"
      @emitScroll="emitScroll"
      :scrollDom="scrollRef"
      :scrollLeftNum="store.homeScrollLeft"
    />
    <progressCom2
      v-if="!store.previewModeShow && store.previewMode === 2"
      @emitScroll="emitScroll"
      :scrollDom="scrollRef"
      :scrollLeftNum="store.homeScrollLeft"
    />
  </div>
  <!-- <ExhibitsDialog :attachDom="scrollRef" /> -->
  <MenuNavigation />
  <div class="audio-play" @click="setPlayType" v-if="store.isUploadRadio">
    <i class="doorIcon" v-if="!store.audioPlayType">&#xe688;</i>
    <i class="doorIcon" v-else>&#xe671;</i>
  </div> 
  <!-- <threeRole /> -->
</template>
 
<script setup lang="ts">
import nextModuleCom from '@/freeComponents/nextModule/index.vue';
import moveComponents from '@/freeComponents/style15Com/move.vue';
import threeRole from '@/freeComponents/threeRole/index.vue';
import progressCom from '../../freeComponents/progress/index.vue';
import progressCom2 from '../../freeComponents/progress/pprogressMode.vue';
import { saveConfig } from '@/api/templates/templates';
import { urls } from '@/utils/request/upload';
// import ExhibitsDialog from '@/freeComponents/exhibitsDialog/index.vue';
import Footer from '@/freeComponents/Footer/index.vue';
import MenuNavigation from '@/freeComponents/menuNavigation/index.vue';
// https://static.jiyi.show/free/sceneBackground/freeBg1.jpg
import {
  getOriginallyBg,
  sceneAll,
  sceneBackgroundList,
  sceneTwoBackgroundList,
  sceneFourBackgroundList,
} from '@/material/index';
import { psthOutline } from '@/hooks/menuHooks';
import posterComponent from '@/freeComponents/poster/index.vue';
import { getActiveBorder } from '@/hooks/menuHooks';
import Level1outline from '../../freeComponents/Level1outline/Level1outline.vue';
import { getRemNumber } from '@/utils/getRemComputed';
import { ref, onMounted, watch, nextTick, onUnmounted, onActivated, computed } from 'vue';
import { useProjectStore } from '@/store';
import { mouseMove } from '@/hooks/index';
import { storeToRefs } from 'pinia';
import { commonDataStore } from '@/store';
import { useRoute } from 'vue-router';
import { isAndroid } from '@/hooks/index.ts';
import { projectDetail } from '@/api/project/project';
import { shearInit } from '@/hooks/wxShare.ts';
import { publicUrls } from '@/utils/minxin';

const isAndroidType = isAndroid();
const interval = ref(null);
const scrollTimer = ref(null);
const route = useRoute();
const listContainer = ref();
const itemContainer = ref([]);
const commonStore = commonDataStore();
const store = useProjectStore();
const { templateMOdeList, updateType, previewModuleIndex } = storeToRefs(store);
const scrollRef = ref();
const startX = ref(0);
const endX = ref(0);
const startY = ref(0);
const scrollLock = ref(false);
const timer = ref();
const pageWheel = (event: any) => {
  const delta = Math.sign(event.wheelDelta || -event.detail);

  if (delta > 0) {
    if (scrollRef.value.scrollLeft === 0) {
    } else {
      scrollRef.value.scrollLeft = scrollRef.value.scrollLeft - 100;
    }
  } else {
    scrollRef.value.scrollLeft = scrollRef.value.scrollLeft + 100;
  }
  event.preventDefault();

  // scrollRef
};
const expandItem = (id: number, index: number) => {
  if (store.previewModuleIndex === index) {
    {
      return;
    }
  }
  store.previewModuleIndex = index;
  setTimeout(() => {
    psthOutline('Level1outline' + id);
  }, 100);
};
const startDrag = () => {
  event.preventDefault();
};
const onContextMenuStop = () => {
  event.preventDefault();
};
const endDrag = () => {
  // store.bannerShow = true;
  // setTimeout(() => {
  //   store.bannerLock = true;
  // }, 900);
  event.preventDefault();
};
const handleTouchStart = (e) => {
  startY.value = e.touches[0].pageY;
};

const handleTouchMove = (e) => {
  const currentY = e.touches[0].pageY;
  let isScrollingDown = currentY > startY.value + 20;
  console.log(isScrollingDown);
  if (isScrollingDown && (window.pageYOffset === 0 || document.documentElement.scrollTop === 0)) {
    e.preventDefault(); // 阻止默认行为
  }
};
const onTouchStart = (e) => {
  startX.value = e.touches[0].clientX;
  event.preventDefault();
};
const preventPullToRefresh = (e) => {
  // 阻止默认的上拉刷新行为
  // 你可以在这里添加更多的逻辑来判断是否需要阻止
  e.preventDefault();
  e.stopPropagation();
};
const onTouchMove = (e) => {
  endX.value = e.touches[0].clientX;
};
const initName = async () => {
  try {
    let res = await projectDetail(localStorage.getItem('projectId'));
    shearInit(
      res.data.name + (res.data.subTitle ? '——' + res.data.subTitle : ''),
      res.data.coverUrl ? urls + res.data.coverUrl : '',
      res.data.description,
    );
    store.isActivitys = res.data.activityId ? true : false;
    console.log(urls + res.data.coverUrl);
    window.document.title = res.data.name + (res.data.subTitle ? '——' + res.data.subTitle : '');
  } catch (err) {
    console.log(err, '1101111111');
  }
};
initName();
const onTouchEnd = (e) => {
  if (endX.value < startX.value) {
    // 左滑
  } else if (endX.value > startX.value) {
    if (scrollRef.value.scrollLeft === 0) {
      store.bannerShow = true;
      store.bannerLock = true;
    }
  }
  // event.preventDefault();
  // 重置初始值
  startX.value = 0;
  endX.value = 0;
};
store.getStyleInfo();
store.getFreeInfoData();
const getFreeBackground = computed(() => {
  let bgc: string;
  if (commonStore.templateId) {
    bgc = getOriginallyBg(commonStore.templateId);
  }
  // switch (commonStore.templateId) {
  //   case 546821049266245:
  //     bgc = sceneAll[0];
  //     break;
  //   case 568727972499525:
  //     bgc = sceneAll[1];
  //     break;
  //   case 581876609753157:
  //     bgc = sceneAll[2];
  //     break;
  //   case 584041224159301:
  //     bgc = sceneAll[3];
  //     break;
  //   case 594187892883525:
  //     bgc = sceneAll[4];
  //     break;
  //   default:
  //     bgc = sceneBackgroundList[0];
  //     break;
  // }
  if (store.styleInfo) {
    if (store.styleInfo.backgroundImage) {
      bgc = store.styleInfo.backgroundImage;
    } else {
      // store.styleInfo.backgroundImage = bgc;
      // setTimeout(() => {
      //   saveConfig(localStorage.getItem('projectId'), store.styleInfo);
      // }, 4000);
    }
  }

  return bgc;
});
onMounted(() => {
  mouseMove('edit-scroll-box');
  getActiveBorder();
  // console.log(commonStore.templateId,'获取id')
});
onActivated(() => {
  mouseMove('edit-scroll-box');
  nextTick(() => {
    // console.log(store.homeScrollLeft);
    if (store.homeScrollLeft !== 0) {
      scrollRef.value.scrollLeft = store.homeScrollLeft;
    }
  });

  getActiveBorder();
});
onMounted(() => {
  // window.addEventListener('keydown', handleKeyDown);
});
onUnmounted(() => {
  // window.removeEventListener('keydown', handleKeyDown);
});
const handleKeyDown = (event) => {
  // 监听键盘事件，实现Ctrl+Z撤销
  if (event.ctrlKey && event.key === 'z') {
    event.preventDefault(); // 阻止默认的撤销行为（例如在浏览器中撤销输入）
    // store.fallbackAction();
  }
  if (event.ctrlKey && event.key === 'y') {
    event.preventDefault(); // 阻止默认的撤销行为（例如在浏览器中撤销输入）
    // store.recovery();
  }
};
const scrollDom = () => {
  store.homeScrollLeft = scrollRef.value.scrollLeft;

  const scrollX = scrollRef.value.scrollLeft;
  // 视差因子，控制背景移动速度，值越小移动越慢
  const parallaxFactor = 0.08;
  // 计算背景图应移动的位置
  const backgroundPositionX = scrollX * parallaxFactor;

  // 设置背景图的水平位置
  listContainer.value.style.backgroundPositionX = backgroundPositionX + 'px';

  // console.log(store.homeScrollLeft)
  // if (!scrollRef.value || !itemContainer.value) return;
  // const containerRect = scrollRef.value.getBoundingClientRect();
  // itemContainer.value.forEach((element, index) => {
  //   const rect = element.getBoundingClientRect();

  //   // const isVisible =
  //   //   rect.top >= containerRect.top &&
  //   //   rect.top <= containerRect.bottom &&
  //   //   rect.right >= containerRect.left &&
  //   //   rect.left <= containerRect.right;
  //   //   store.setItemHidden(isVisible,index)
  //   // console.log(`子元素是否在视口内: ${isVisible}${index}`);
  // });
  clearTimeout(scrollTimer.value);
  scrollTimer.value = setTimeout(() => {
    getScrollAppearDom();
  }, 100);
  // getScrollAppearDom();
};
const getScrollAppearDom = () => {
  if (!scrollRef.value || !itemContainer.value) return;
  const containerRect = scrollRef.value.getBoundingClientRect();
  let closestElementIndex = 0;
  let dom = null;
  //判断当前滚动区域距离最近的元素
  if (scrollRef.value) {
    const containerRight = scrollRef.value.getBoundingClientRect().right;
    let minDistance = Infinity;
    const itemElements = scrollRef.value.querySelectorAll('.outlineClassName');
    itemElements.forEach((element, index) => {
      //判断元素是否在视口区域
      const rect = element.getBoundingClientRect();

      const isVisible =
        rect.top >= containerRect.top &&
        rect.top <= containerRect.bottom &&
        rect.right >= containerRect.left &&
        rect.left <= containerRect.right;
      //判断距离右侧的距离
      const itemRight = element.getBoundingClientRect().right;
      const distance = Math.abs(containerRight - itemRight);
      if (distance < minDistance && isVisible) {
        minDistance = distance;
        closestElementIndex = index;
        dom = element;
      }
    });
    if (dom && dom.dataset && dom.dataset.userId) {
      // let id = dom.id.replace('outlineClassName', '');
      store.audioPlayId = dom.dataset.userId;
      store.audioPlayUserType = dom.dataset.userType;
      if (dom.dataset.userUrl) {
        let audioUrl = urls + dom.dataset.userUrl;
        if (store.audioPlayUrl == audioUrl) {
          return;
        } else {
          store.audioPlayUrl = audioUrl;
          if (store.audioPlayType) {
            store.audioDomOperate();
          }
        }
      }

      //  store.audioDomOperate()
      console.log(dom.dataset.userUrl);
    }
    // console.log('Closest element index:', closestElementIndex);
  }
};
const setPlayType = () => {
  store.setAudioPlayType();
};
const emitScroll = (scrollLeftNumber: number) => {
  //进度条传递参数并将滚动距离传递
  scrollRef.value.scrollLeft = scrollLeftNumber;
};

watch(
  () => templateMOdeList,
  () => {
    // console.log('更新')
    nextTick(() => {
      getActiveBorder();
    });
  },
  { deep: true },
);
watch(
  () => updateType,
  () => {
    // console.log(store.homeScrollLeft)
    setTimeout(() => {
      nextTick(() => {
        scrollRef.value.scrollLeft = store.homeScrollLeft;
      });
    }, 60);
  },
  { deep: true },
);

watch(
  () => route,
  () => {
    // console.log(store.homeScrollLeft)
    if (store.audioPlayType) {
      store.audioDomOperateStop();
    }
  },
  { deep: true },
);
</script>

<style lang="less" scoped>
.home-box {
  cursor: pointer;
  min-width: 100%;
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;

  -webkit-overflow-scrolling: touch;
  //  scroll-behavior: smooth;
  transition: all 0.4s;
  scrollbar-width: none;
}
.home-box::-webkit-scrollbar {
  display: none;
}

.scroll-box {
  display: flex;
  flex-wrap: nowrap;
  position: relative;

  // min-width: 100vw;

  // width: auto;
}

.scroll-box-item-parent {
  // position: relative;
  transition: all 0.3s ease-out;
  display: flex;
  // background-image: url(https://static-1316349889.cos.ap-shanghai.myqcloud.com/door/ziyouwebp.webp);
  background-size: auto 100%;
  background-repeat: repeat;
}
.scroll-box-item {
  width: auto;
  &:nth-child(2) {
    :deep(.outline-style2) {
      margin-left: 1px !important;
    }
  }
}
.home-box-Android {
  overflow: auto !important;
  overflow-y: auto !important;
  :deep(.scroll-box-item) {
    width: auto;
    overflow-y: hidden;
  }
}
.home-box-Ios {
  overflow-y: hidden !important;
}
.home-box-loop {
  :deep(.hovered) {
    border-color: transparent !important;
  }
  :deep(.border-hover-style) {
    border: none;
    border-left: 0;
  }
}
.scroll-box {
  :deep(.t-dialog) {
    padding: 0;
    background: transparent;
    border: none;
  }
  :deep(.t-dialog__header) {
    display: none;
  }
  :deep(.t-dialog__footer) {
    display: none;
  }

  :deep(.t-dialog__body) {
    padding: 0;
    overflow: visible;
    display: flex;
    justify-content: center;
    align-content: center;
  }
}
.audio-play {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  bottom: 40px;
  left: 15px;
  width: 40px;
  height: 40px;
  background: #e62b17;
  border-radius: 50%;
  z-index: 88;
  i {
    font-size: 28px;
    line-height: 28px;
    color: #fff;
  }
}
.scroll-box-item-parent-2 {
  position: relative;
}
.shadow-box {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 66666;
  background-size: auto 100%;
  background-repeat: repeat;
  display: none;
}
.shadow-box-move {
  display: block;
  animation: fadeOut 2s forwards;
}
@keyframes fadeOut {
  0% {
    opacity: 1;
    transform: calc(1);
  }
  10% {
  }
  100% {
    opacity: 0;
    transform: calc(2);
  }
}
.scroll-box-item-parent-mode {
  :deep(.scroll-box-item) {
    // min-width: 1240px;
  }
}
.free-item-style {
  display: flex;
  width: auto;
  // transition: width 6s;
}
.free-item-move {
  max-width: 100px;
  overflow: hidden;
}
.free-item-move-pw {
  width: auto;
  max-width: auto;
}
.left-title-box {
  position: relative;
  z-index: 50;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background: rgba(0, 0, 0, 0.4);
  width: 99px;
  height: 100%;
  writing-mode: vertical-rl;
  text-orientation: upright;
  text-align: center;
  letter-spacing: 3px;
  font-size: 24px;
  font-family: SourceHanSerifCN-Bold;
  color: #fff;
  margin-right: 1px;
}
</style>
